#include "../source/server.hpp"

// 管理所有的连接
std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;
EventLoop base_loop;

LoopThreadPool *loop_pool;

void ConnectionDestroy(const PtrConnection &conn)
{
    _conns.erase(conn->Id());
}

void OnConnected(const PtrConnection &conn)
{
    DBG_LOG("NEW CONNECTION: %p", conn.get());
}

void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadableSize());
    std::string str = "我收到了客户端发送的消息";
    conn->Send(str.c_str(), str.size());
    conn->Shutdown(); // 通信一次直接关闭连接
}

void NewConnection(int fd)
{
    conn_id++;
    PtrConnection conn(new Connection(loop_pool->NextLoop(), conn_id, fd));
    conn->SetMessageCallBack(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetClosedCallBack(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallBack(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10);
    conn->Established();
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("NEW CONNECTION...");
}

int main()
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();

    Acceptor acceptor(&base_loop, 8500);

    acceptor.SetAcceptCallBack(std::bind(NewConnection, std::placeholders::_1)); // 设置完回调函数
    acceptor.Listen();                                                           // 开始监听
    base_loop.Start();

    return 0;
}